package com.fypg.module.medical.service.department;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.fypg.module.medical.controller.admin.department.vo.*;
import com.fypg.module.medical.dal.dataobject.department.DepartmentDO;
import com.fypg.framework.common.pojo.PageResult;
import com.fypg.framework.common.pojo.PageParam;
import com.fypg.framework.common.util.object.BeanUtils;

import com.fypg.module.medical.dal.mysql.department.DepartmentMapper;

import static com.fypg.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.fypg.framework.common.util.collection.CollectionUtils.convertList;
import static com.fypg.framework.common.util.collection.CollectionUtils.diffList;
import static com.fypg.module.medical.enums.ErrorCodeConstants.*;

/**
 * 科室信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public String createDepartment(DepartmentSaveReqVO createReqVO) {
        // 插入
        DepartmentDO department = BeanUtils.toBean(createReqVO, DepartmentDO.class);
        departmentMapper.insert(department);
        // 返回
        return department.getId();
    }

    @Override
    public void updateDepartment(DepartmentSaveReqVO updateReqVO) {
        // 校验存在
        validateDepartmentExists(updateReqVO.getId());
        // 更新
        DepartmentDO updateObj = BeanUtils.toBean(updateReqVO, DepartmentDO.class);
        departmentMapper.updateById(updateObj);
    }

    @Override
    public void deleteDepartment(String id) {
        // 校验存在
        validateDepartmentExists(id);
        // 删除
        departmentMapper.deleteById(id);
    }

    @Override
        public void deleteDepartmentListByIds(List<String> ids) {
        // 校验存在
        validateDepartmentExists(ids);
        // 删除
        departmentMapper.deleteByIds(ids);
        }

    private void validateDepartmentExists(List<String> ids) {
        List<DepartmentDO> list = departmentMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEPARTMENT_NOT_EXISTS);
        }
    }

    private void validateDepartmentExists(String id) {
        if (departmentMapper.selectById(id) == null) {
            throw exception(DEPARTMENT_NOT_EXISTS);
        }
    }

    @Override
    public DepartmentDO getDepartment(String id) {
        return departmentMapper.selectById(id);
    }

    @Override
    public PageResult<DepartmentDO> getDepartmentPage(DepartmentPageReqVO pageReqVO) {
        return departmentMapper.selectPage(pageReqVO);
    }

}